﻿using UnityEngine;
using System.Collections;

public class GrenadeExplosion : MonoBehaviour
{
    private Weapon weapon;

    public GameObject explosionPrefab;
    public float lifetime;
    public float radius = 5.0F;
    public float power = 10.0F;
    // Use this for initialization
    void Start ()
    {
        weapon = GameObject.FindGameObjectWithTag ("Weapon").GetComponent<Weapon> ();    
    }
    
    // Update is called once per frame
    void Update ()
    {        
        lifetime -= Time.deltaTime;
        
        if (lifetime < 0) {        
            Explode ();
            RemoveObject ();
        }
    }

    private void Explode ()
    {
        Debug.Log ("What Sound is this: " + weapon.weaponSounds [2]);
        //weapon.Rocket.rigidbody.AddExplosionForce (300, weapon.Rocket.rigidbody.position, 30, 10, ForceMode.Impulse);
        GameObject explosion = (GameObject)Instantiate (explosionPrefab, this.transform.position, this.transform.rotation); 
        AudioSource.PlayClipAtPoint (weapon.weaponSounds [2], transform.position);
        
        Vector3 explosionPos = transform.position;
        Collider[] colliders = Physics.OverlapSphere (explosionPos, radius);
        foreach (Collider hit in colliders) {
            if (hit.rigidbody)
                //Kör en raycast för att se om objekt ligger bakom väggar
                hit.rigidbody.AddExplosionForce (power, explosionPos, radius, 0, ForceMode.Impulse);
        }
    }

    void RemoveObject ()
    {
        Destroy (gameObject);
    }
}